package com.taru.houseapp.filter;



import com.alibaba.fastjson.JSON;
import com.taru.houseapp.commen.JsonResult;
import com.taru.houseapp.until.JwtUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component("tokenIsValidFilter")
public class TokenIsValidFilter implements Filter {

    String [] loginURIs;
    public TokenIsValidFilter() {
        System.out.println("Filter加载时机");
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //获取初始化参数（init-param）(key-value形式)
        loginURIs=filterConfig.getInitParameter("exclude").split(",");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest)servletRequest;//向下转型
        HttpServletResponse response=(HttpServletResponse) servletResponse;
        //获取请求方式类型
        String method=request.getMethod();
        if(method.equals("get") || method.equals("GET")){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        //放行登录请求，让其获取签发的token
        String loginURI=request.getRequestURI();//返回除去host（域名或者ip）部分的路径 /login

        for (int i=0;i<loginURIs.length;i++){
            if(loginURI.endsWith(loginURIs[i])){
                filterChain.doFilter(servletRequest,servletResponse);
                return;
            }
        }
        //获取请求头中的token 通过key-value形式
        String token=request.getHeader("Authorization");
        if(token!=null){
            try {
                JwtUtil.verifyToken(token.substring(7));
                filterChain.doFilter(servletRequest,servletResponse);
                return;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        JsonResult result=new JsonResult(401,"没有登录或者token过期");
        String jsonStr= JSON.toJSONString(result);
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        PrintWriter pw=response.getWriter();
        pw.write(jsonStr);
        pw.flush();
        pw.close();

    }

    @Override
    public void destroy() {
        System.out.println("销毁Filter");
    }
}
